
#include "image_subset.h"
#include "util/log.h"		    // log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    // Needs to come in early


#include <cassert>

ImageSubset::ImageSubset(unsigned int _Width, unsigned int _Height, float _FrameTime)
{
    m_Width = _Width;
    m_Height = _Height;
    m_FrameTime = _FrameTime;

    // Default frame Count
    m_FrameC = m_Width * m_Height;

    // allocate memory
    m_FrameA = new FrameInfo[m_FrameC];

    // Setup frame info
    math::Vec2  Min = math::Vec2(0.00f, 0.00f);
    math::Vec2  Max = math::Vec2(1.0f, 1.0f);

/* Need borders ?
    math::Vec2  Min = math::Vec2(0.02f, 0.02f);
    math::Vec2  Max = math::Vec2(0.98f, 0.98f);
*/

    math::Vec2  Delta = Max - Min;
    
    Delta.x /= (float)m_Width;
    Delta.y /= (float)m_Height;

    for (unsigned short x = 0; x<m_Width; x++)
    {
        for (unsigned short y = 0; y<m_Height; y++)
        {
            FrameInfo* pFrame = GetFrame(x, y);
            pFrame->UV1 = Min + math::Vec2(Delta.x * (float)x, Delta.y * (float)y);
            pFrame->UV2 = Min + math::Vec2(Delta.x * (float)(x+1), Delta.y * (float)(y+1));
        }
    }
}

ImageSubset::~ImageSubset()
{
    UTIL_SAFE_DELETEA(m_FrameA);
}


ImageSubset::FrameInfo*  ImageSubset::GetFrame(unsigned short X, unsigned short Y)
{
    assert(X < m_Width && Y < m_Height && "Trying to access an illegal frame");
    return &m_FrameA[X + (Y * m_Width)];
}

void            ImageSubset::GetSubImage(float _Time, math::Vec2& _UV1, math::Vec2& _UV2)
{
    GetSubImage((unsigned int)(_Time / m_FrameTime), _UV1, _UV2);
}

void            ImageSubset::GetSubImage(unsigned int _FrameID, math::Vec2& _UV1, math::Vec2& _UV2)
{
    unsigned short Frame = _FrameID % m_FrameC;
    FrameInfo* pFrame = &m_FrameA[Frame];
    _UV1 = pFrame->UV1;
    _UV2 = pFrame->UV2;
}

void            ImageSubset::SetFrameC(unsigned short _FrameC)
{
    unsigned short Max = m_Width * m_Height;
    assert(_FrameC <= Max && "Trying to set Subset frame count to an illegal number");
    m_FrameC  = _FrameC ;
    
    if (m_FrameC > Max)
        m_FrameC = Max;
}
